<template>
  <div class="login">
    <el-form
    ref="form"
    :model="form"
    label-width="80px"
    label-position="top"
    :rules="rules">
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密 码" prop="password">
        <el-input
        v-model="form.password"
        type="password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
        type="primary"
        @click="onSubmit"
        :loading="isLoginLoading"
        >登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/services/user'

export default {
  name: 'LoginIndex',
  data () {
    return {
      form: {
        phone: '18201288771',
        password: '111111'
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度为6到18个字符', trigger: 'blur' }
        ]
      },
      // 按键点击状态
      isLoginLoading: false
    }
  },
  methods: {
    // 登录功能
    async onSubmit () {
      try {
        // 设置成功后的功能请求
        await this.$refs.form.validate()
        // 发送请求
        // console.log(qs.stringify(this.form))
        // 设置按钮加载中
        this.isLoginLoading = true
        const { data } = await login(this.form)
        // 取消加载状态
        this.isLoginLoading = false
        // 响应处理
        if (data.state !== 1) {
          // return alert(data.message)
          return this.$message.error(data.message)
        }
        // $router是vueRouter提供的方法
        this.$message.success(data.message)
        // 将用户信息存储到VueX中
        this.$store.commit('setUser', data.content)
        // 跳转路由
        this.$router.push(
          this.$route.query.redirect || '/'
        )
      } catch (err) {
        // 设置失败后的功能提示
        console.log('验证失败')
      }
    }
  }
}
</script>

<style lang='scss' scoped>
  .login {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    .el-form {
      background-color: #fff;
      width: 300px;
      padding: 20px;
      border-radius: 10px;
      .el-button {
        width: 100%;
      }
    }
  }
</style>
